package me.ywy.skin.skincore;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.support.v4.view.LayoutInflaterCompat;
import android.view.LayoutInflater;

import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;

/**
 * Created by ywy on 2018-04-25.
 */
public class SkinActivityLifecycle implements Application.ActivityLifecycleCallbacks {

    HashMap<Activity , SkinLayoutFactory> mLayoutFactoryHashMap = new HashMap<>();

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        LayoutInflater layoutInflater = LayoutInflater.from(activity);
        try {
            Field field = LayoutInflater.class.getDeclaredField("mFactorySet");
            field.setAccessible(true);
            field.setBoolean(layoutInflater , false);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        SkinLayoutFactory skinLayoutFactory = new SkinLayoutFactory();
        LayoutInflaterCompat.setFactory2(layoutInflater , skinLayoutFactory);

        SkinManager.getInstance().addObserver(skinLayoutFactory);
        mLayoutFactoryHashMap.put(activity , skinLayoutFactory);
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

        SkinLayoutFactory skinLayoutFactory = mLayoutFactoryHashMap.remove(activity);
        SkinManager.getInstance().deleteObserver(skinLayoutFactory);

    }
}
